<template>
  <div>
    <el-collapse-transition>
      <div v-show="btnGroup.search" class="main-box search-box">
        <el-form
          class="troila-form"
          ref="searchInfo"
          :model="searchObj"
          :inline="true"
          label-width="100px"
        >
          <el-form-item
            label="登录地址"
            prop="ipadress"
            class="troila-select-inline"
          >
            <el-input
              v-setwidth
              placeholder="请输入登录地址"
              v-model="searchObj.ipadress"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item
            label="登录名称"
            prop="loguser"
            class="troila-select-inline"
          >
            <el-input
              v-setwidth
              placeholder="请输入登录名称"
              v-model="searchObj.loguser"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item
            label="登录状态"
            prop="state"
            class="troila-select-inline"
          >
            <el-select
              v-setwidth
              placeholder="请选择"
              v-model="searchObj.state"
              clearable
              popper-class="troila-popper"
            >
              <el-option
                v-for="(item, index) in loginStatusList"
                :key="index"
                :label="item.dictName"
                :value="item.dictCode"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="登录时间" class="troila-select-inline">
            <el-date-picker
              v-model="time"
              v-setwidth
              placeholder="请选择"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              value-format="yyyy-MM-dd"
              @change="changeDate"
              type="daterange"
              popper-class="troila-popper"
            ></el-date-picker>
          </el-form-item>
          <el-form-item class="searchBtn">
            <el-button class="cancelBtn" @click="resetForm">重置</el-button>
            <el-button type="primary" @click="submitSearch">搜索</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-collapse-transition>
    <div class="troila-group">
      <select-group
        v-model="btnGroup"
        :row="allTitle"
        :row-choose="chooseTitle"
        @rowChange="
          (arr) => {
            chooseTitle = arr
          }
        "
        @refresh="getList"
      />
    </div>
    <div class="main-box table-box">
      <div class="table-box-title ClearFloat">
        <i class="title-font">查询结果</i>
        <div class="troila-form">
          <!--  <el-button type="primary">导入</el-button> -->
          <el-button
            type="primary"
            v-limit="`system:logManage:login:export`"
            @click="exportLog"
            >导出</el-button
          >
          <el-button
            type="primary"
            v-limit="`system:logManage:login:batchDel`"
            @click="btnClick('batchDel')"
            >批量删除</el-button
          >
          <el-button
            type="primary"
            v-limit="`system:logManage:login:clear`"
            @click="clearLog"
            >清空</el-button
          >
          <!--  <el-button type="primary">新增</el-button> -->
        </div>
      </div>
      <unit-table
        v-if="!btnGroup.card"
        selection
        index
        :loading="loading"
        :title="tableTitle"
        :data="tableData"
        :operation="tableOperation"
        :dictionary="dictionary"
        @return="tableReturn"
        :page="pager.page"
      />
      <unit-cards
        v-if="btnGroup.card"
        selection
        :loading="loading"
        :title="tableTitle"
        :data="tableData"
        :operation="tableOperation"
        :dictionary="dictionary"
        @return="tableReturn"
        :page="pager.page"
      />
      <pagination
        v-show="pager.total > pager.size"
        :pager="pager"
        @query="getList"
        ref="Pagerpagination"
      ></pagination>
    </div>
  </div>
</template>
<script>
import { downloadFile } from '@/assets/js/utils'
import { grobalbaseUrl } from '@/https/api/baseUrl'
export default {
  name: 'login',
  data() {
    return {
      searchObj: {
        ipadress: '',
        loguser: '',
        state: '',
        beginTime: '',
        endTime: '',
      }, //搜索参数
      searchRes: {}, //搜索储存值
      loading: false,
      time: null, //时间组件值
      btnGroup: {
        //按钮组
        search: true,
        refresh: false,
        card: false,
      },
      pager: {
        // 页码
        total: 0,
        page: 1, //当前第几页
        size: 10, //每页显示的条数
      },
      dictionary: {
        // 字典信息
        // state: [
        //     { dictName: '成功', dictCode: '1' },
        //     { dictName: '失败', dictCode: '0' },
        // ],
      },
      allTitle: [
        // 全部可显示表头
        {
          label: '登录名称', //*表头名称
          code: 'loguser', //*对应数据项
          tooltip: true, //超出显示浮层
          sort: true, //是否显示排序
          width: 110, //最小宽
        },
        {
          label: '登录地址',
          code: 'ipadress',
          tooltip: true,
          width: 110,
        },
        /*  {
            label: '登录地点',
            code: 'loglocal',
            tooltip: true,
            width: 110,
        }, */
        {
          label: '浏览器',
          code: 'browser',
          tooltip: true,
          width: 110,
        },
        {
          label: '操作系统',
          code: 'operating',
          tooltip: true,
        },
        {
          label: '登录状态',
          code: 'state',
          dict: 'state',
          style: {
            color: { value: '#FF4A4A', result: 0 },
          },
        },
        // {
        //   label: '操作信息',
        //   code: 'state',
        //   dict: 'state',
        //   style: {
        //     color: { value: '#FF4A4A', result: 0 },
        //   },
        // },
        {
          label: '登录时间',
          code: 'createtime',
          tooltip: true,
          sort: true,
          width: 110,
          format: (item, key) => {
            return this.toTime(item[key])
          },
        },
      ],
      chooseTitle: [
        //被选中显示表头
        'loguser',
        'ipadress',
        /*  'loglocal', */
        'browser',
        'operating',
        'state',
        'msg',
        'createtime',
      ],
      tableData: [
        //表格数据
        /* {
            loguser: '周瑜',
            ipadress: '172.0.0.1',
            loglocal: '内网IP',
            browser: '那个',
            operating: '火球',
            state: 1,
            msg: '登录成功',
            createtime: '2020-07-16 16:17'
        },
        {
            loguser: '诸葛亮',
            ipadress: '172.0.0.1',
            loglocal: '内网IP',
            browser: '那个哈',
            operating: '11',
            state: 2,
            msg: '登录失败',
            createtime: '2020-07-16 16:17'
        } */
      ],
      tableOperation: [
        //表格操作
        // *code 对应图标, label 对应浮层显示文字, show 判断是否显示, color 图标颜色
        /*  'edit',
        { code: 'refresh', label: '重置密码', show: () => { } }, */
        {
          code: 'delete',
          color: '#D13633',
          limit: 'system:logManage:login:delete',
        },
      ],
      selection: [],
    }
  },
  computed: {
    tableTitle() {
      //表格表头
      return this.allTitle.filter(
        (item) => this.chooseTitle.indexOf(item.code) > -1
      )
    },
    loginStatusList() {
      let list = this.$store.state.dictionary.login_status
      if (!list) {
        this.$store.dispatch('dictionary/getDict', 'login_status')
      }
      this.dictionary.state = list
      return list ? list : []
    },
  },
  methods: {
    // 获取列表
    getList() {
      let param = {
        pageNum: this.pager.page,
        pageSize: this.pager.size,
        ...this.searchRes,
      }
      this.loading = true
      setTimeout(() => {
        this.loading = false
        this.pager.total = 4
        this.tableData = [{}, {}, {}, {}]
      }, 100)
      return
      this.API.logManage
        .pageListLogin(param)
        .then((res) => {
          // console.log(res)
          if (res.code === 1) {
            this.loading = false
            this.pager.total = res.data.total ? res.data.total : 0
            this.tableData = res.data.records
          } else {
            this.loading = false
          }
        })
        .catch((e) => {
          // console.log(e)
          this.loading = false
        })
    },
    // 日期控件操作
    changeDate() {
      // console.log(this.time)
    },
    // 重置
    resetForm() {
      this.$refs.searchInfo.resetFields()
      this.searchObj.beginTime = ''
      this.searchObj.endTime = ''
      // this.searchObj = {}
      this.time = []
      this.searchRes = {}
      this.pager.page = 1
      this.getList()
    },
    // 搜索
    submitSearch(method) {
      this.searchRes = {
        ...this.searchObj,
        beginTime: this.time && this.time.length > 0 ? this.time[0] : '',
        endTime: this.time && this.time.length > 0 ? this.time[1] : '',
      }
      this.pager.page = 1
      this.getList()
    },
    // 按钮操作
    btnClick(method) {
      // console.log(method)
      let text = ''
      switch (method) {
        case 'batchDel':
          text = '删除'
          break
        default:
          return
      }
      let name = this.selection.map((v) => `${v.loguser}`)
      // console.log(name)
      this.selection.length > 0
        ? this.$confirmFn(
            `您确定${text}以下记录吗？<div>${name.join('、')}</div>`,
            '提示',
            {
              callback: (action, instance) => {
                if (action == 'cancel ') {
                  return
                } else if (action == 'confirm') {
                  // console.log(this.selection)
                  let idList = this.selection.map((v) => v.id).join(',')
                  this.deleteLog({ ids: idList })
                }
              },
            }
          )
        : this.$alertFn.error(`请选择需要${text}的数据 ！`)
    },
    // 表格操作
    tableReturn(method, { row, prop, order, selection }) {
      // console.log(method, row, prop, order, selection)
      let text = '',
        text_ = ''
      switch (method) {
        case 'selection':
          this.selection = [...selection]
          return
        case 'delete':
          text_ = `您确定删除<span class='light'>${row.loguser}</span>这条记录吗？`
          break
        default:
          return
      }
      this.$confirmFn(text_, '提示', {
        callback: (action, instance) => {
          if (action == 'cancel ') {
            return
          } else if (action == 'confirm') {
            // console.log(method, row)
            this.deleteLog({ ids: row.id.toString() })
          }
        },
      })
    },
    //清空日志
    clearLog() {
      this.$confirmFn(`您确定清空全部记录吗？`, '提示', {
        callback: (action, instance) => {
          if (action == 'cancel ') {
            return
          } else if (action == 'confirm') {
            this.deleteLog({ ids: 'all' })
          }
        },
      })
    },
    //删除日志
    deleteLog(dataList) {
      this.API.logManage
        .removeLogin(dataList)
        .then((res) => {
          // console.log(res)
          if (res.code === 1) {
            this.getList()
            this.$alertFn.success(
              `${dataList.ids == 'all' ? '清空' : '删除'}成功 ！`
            )
          } else {
            this.$alertFn.error(
              `${dataList.ids == 'all' ? '清空' : '删除'}失败，请稍后再试 ！`
            )
          }
        })
        .catch((e) => {
          // console.log(e)
          // this.$alertFn.error(
          //   `${dataList.ids == 'all' ? '清空' : '删除'}失败，请稍后再试 ！`
          // )
        })
    },
    //导出日志
    exportLog() {
      let params = {
        ...this.searchObj,
        beginTime: this.time && this.time.length > 0 ? this.time[0] : '',
        endTime: this.time && this.time.length > 0 ? this.time[1] : '',
      }
      this.API.logManage
        .exportLogin(params)
        .then((res) => {
          // console.log(res)
          if (res.data) {
            // window.location.href=`${grobalbaseUrl.baseUrl}/download/${res.data}/操作日志`;
            downloadFile(
              `${grobalbaseUrl.baseUrl}/download/${res.data}/导出日志`,
              null,
              'url'
            )
          } else {
            this.$alertFn.error('导出失败')
          }
        })
        .catch((e) => {
          // this.$alertFn.error('导出失败')
        })
    },
  },
  created() {
    this.getList()
  },
  mounted() {},
  destroyed() {},
}
</script>
<style scoped>
</style>
